<?php
namespace App\Admin\Controllers\Stocking;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SysArea;
use App\Models\Product\ProductClassify;
use App\Models\Stocking\StockingApply;
use App\Models\Stocking\StockingApplyDetail;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

class SearchController extends AdminController{

    protected $title = '备货单';

    protected function grid()
    {
        $grid = new Grid(new StockingApply());
        $grid->model()->orderBy('id', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->commit_date = $item->detail->max('commit_date');
            }
            return $collection;
        });
        $grid->column('stocking_no','备货单号')->totalRow('TTL')->expand(function ($model) {
            $details = $model->detail->map(function($item) use ($model){
                    if($model->psku_id == $item->psku_id){
                        return [
                            $model->sku->psku_code ?? '',
                            $model->sku->psku_cn ?? '',
                            $item->apply_detail_num,
                            $item->commit_date,
                            StockingApplyDetail::$_status[$item->status],
                        ];
                    }else{
                        return [
                            $item->sku->psku_code ?? '',
                            $item->sku->psku_cn ?? '',
                            $item->apply_detail_num,
                            $item->commit_date,
                            StockingApplyDetail::$_status[$item->status],
                        ];
                    }
            })->toArray();
            return new Table(['SKU', '名称','备货数量', '交期', '状态'], $details);
        });
        $grid->column('area.area','站点');
        $grid->column('seller_id','备货员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','产品名称')->style('max-width:150px');
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('skuClassify.title','品类')->style('max-width:120px');
        $grid->column('apply_num','备货数量')->totalRow();
        $grid->column('status','单据状态')->display(function ($value){
            return StockingApply::$_status[$value];
        })->filter(StockingApply::$_status);
        $grid->column('plan_status','计划状态')->display(function ($value){
            return StockingApply::$_planStatus[$value];
        })->filter(StockingApply::$_planStatus);
        $grid->column('pur_status','采购状态')->display(function ($value){
            return StockingApply::$_purStatus[$value];
        })->filter(StockingApply::$_purStatus);
        $grid->column('re_status','收获状态')->display(function ($value){
            return StockingApply::$_reStatus[$value];
        })->filter(StockingApply::$_reStatus);
        $grid->column('commit_date','预计到货时间');
        $grid->column('amount','备货金额(¥)')->totalRow();

        if(Admin::user()->can('stocking.search.edit')){
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->disableEdit();
            });
        }else{
            $grid->disableActions();
        }
        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('stocking/search-download'));
        });
        $grid->disableCreateButton();
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('stocking_no','备货单');
                $filter->equal('area_id','站点')->select(SysArea::options());
            });
            $filter->column(1/3, function ($filter){
                $filter->equal('seller_id', '备货员')->select(User::getUserOptions());
                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->between('created_at', '创建日期')->datetime();
            });
        });

        return $grid;
    }

    public function destroy($id){
        try{
            DB::beginTransaction();
            $model = StockingApply::query()->findOrFail($id);
            $detailStatus = $model->detail->max('status');
            if($detailStatus != 1){
                return response()->json(['status' => false, 'message' => '已生成下游单据勿删除！']);
            }
            $model->delete();
            DB::commit();
            return response()->json(['status' => true,'message' => '操作成功！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = StockingApply::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if($key == 'created_at'){
                if(isset($_filter['start'])&&$_filter['start']){
                    $query->where('created_at','>=',$_filter['start']);
                }
                if(isset($_filter['end'])&&$_filter['end']){
                    $query->where('created_at','<=',$_filter['end']);
                }
            }
            if(in_array($key,['seller_id','area_id','stocking_no'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['备货单号','站点','备货员','SKU','产品名称','季节性','品类','备货数量','状态','预计到货时间','备货金额(¥)','创建日期'];
        RExcel::exportCsv('备货单',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::_getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private static function _getDownloadData($res)
    {
        $seller = [];
        foreach ($res as $model){
            $sellerId = $model->seller_id ?: 0;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            $temp = [
                $model->stocking_no,
                $model->area->area ?? '',
                $seller[$sellerId],
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                ProductClassify::$_season[$model->skuClassify->season ?? 3],
                $model->skuClassify->title ?? '',
                $model->apply_num ?: 0,
                StockingApply::$_status[$model->status],
                $model->detail->max('commit_date'),
                $model->amount ?: 0,
                $model->created_at,
            ];
            yield $temp;
        }
    }
}
